package com.atguigu.gmall.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class Jsons {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将对象转换为Json字符串
     * @param object
     * @return
     */
    public static String toStr(Object object) {
        String json = null;
        try {
            json = objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("对象{}，Json转换异常，{}", object, e);
        }
        return json;
    }

    /**
     * 将Json字符串转换为对象
     * @param jsonStr
     * @param tf
     * @param <T>
     * @return
     */
    public static<T> T toObj(String jsonStr, TypeReference<T> tf) {
        if ("x".equals(jsonStr)) {
            //以前有人查过但是数据库无此记录
            return null;
        }

        T t = null;
        try {
            t = objectMapper.readValue(jsonStr, tf);
        } catch (JsonProcessingException e) {
            log.error("json字符串{}，转对象异常，{}", jsonStr, e);
            e.printStackTrace();
        }
        return t;
    }

    public static<T> T toObj(String jsonStr, Class<T> tf) {
        if ("x".equals(jsonStr)) {
            //以前有人查过但是数据库无此记录
            return null;
        }

        T t = null;
        try {
            t = objectMapper.readValue(jsonStr, tf);
        } catch (JsonProcessingException e) {
            log.error("json字符串{}，转对象异常，{}", jsonStr, e);
            e.printStackTrace();
        }
        return t;
    }
}
